package com.kyd.push.push;

import com.alibaba.fastjson.JSON;

import com.kyd.push.common.result.Ret;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * PushController
 *
 * @author kejw on 2018/9/28
 */
@Controller
@RequestMapping("/push")
public class PushController {

	@GetMapping
	public String index() {
		return "push";
	}

	@ResponseBody
	@PostMapping("/send")
	public Ret send(PushForm pushForm) {
		PushRequest request = PushRequest.newInstance().setNotification(pushForm.getNotification()).setMessage(pushForm.getMessage());

		try {
			if (StringUtils.isNotBlank(pushForm.getExtras())) {
				Map<String, String> extras = JSON.parseObject(pushForm.getExtras(), Map.class);
				request.addExtras(extras);
			}
		} catch (Exception e) {
			return Ret.fail("extras 格式错误，必须为json格式数据");
		}

		JPushKit.newInstance(pushForm.getAppKey(), pushForm.getMasterSecret()).sendPush(request, pushForm.getRegistrationId());

		return Ret.ok();
	}
}
